package com.liuyucheng.idea_springboot.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

public class ExcelUtil {
    public ExcelUtil() {
    }

    public static Workbook getWorkbook(String[] title, String[][] values) {
        int SHEET_LIMIT = 100000;
        return (Workbook)(values.length <= 100000 ? getXSSFWorkbook(title, values) : getSXSSFWorkbookByThread(title, values));
    }

    public static XSSFWorkbook getXSSFWorkbook(String[] title, String[][] values) {
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("sheet");
        XSSFCellStyle style = wb.createCellStyle();
        style.setAlignment((short)2);
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = null;

        int i;
        for(i = 0; i < title.length; ++i) {
            sheet.autoSizeColumn(i);
            cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(title[i]);
        }

        for(i = 0; i < values.length; ++i) {
            sheet.autoSizeColumn(i);
            row = sheet.createRow(i + 1);

            for(int j = 0; j < values[i].length; ++j) {
                cell = row.createCell(j);
                cell.setCellStyle(style);
                cell.setCellValue(values[i][j]);
            }
        }

        return wb;
    }

    public static void getXSSFWorkbook(String fileName, String[] title, String[][] values, HttpServletResponse response) {
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("sheet");
        XSSFCellStyle style = wb.createCellStyle();
        style.setAlignment((short)2);
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = null;

        int i;
        for(i = 0; i < title.length; ++i) {
            sheet.autoSizeColumn(i);
            cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(title[i]);
        }

        for(i = 0; i < values.length; ++i) {
            sheet.autoSizeColumn(i);
            row = sheet.createRow(i + 1);

            for(int j = 0; j < values[i].length; ++j) {
                cell = row.createCell(j);
                cell.setCellStyle(style);
                cell.setCellValue(values[i][j]);
            }
        }

        try {
            setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception var11) {
        }

    }

    public static void getXSSFWorkbook(String[] title, String[][] values, OutputStream outputStream) throws Exception {
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("sheet");
        XSSFCellStyle style = wb.createCellStyle();
        style.setAlignment((short)2);
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = null;

        int i;
        for(i = 0; i < title.length; ++i) {
            sheet.autoSizeColumn(i);
            cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(title[i]);
        }

        for(i = 0; i < values.length; ++i) {
            sheet.autoSizeColumn(i);
            row = sheet.createRow(i + 1);

            for(int j = 0; j < values[i].length; ++j) {
                cell = row.createCell(j);
                cell.setCellStyle(style);
                cell.setCellValue(values[i][j]);
            }
        }

        wb.write(outputStream);
    }

    public static void getXSSFWorkbook(XSSFWorkbook workbook, int sheetNum, String sheetName, String[] title, String[][] values) throws Exception {
        XSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(sheetNum, sheetName);
        XSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment((short)2);
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = null;

        int i;
        for(i = 0; i < title.length; ++i) {
            cell = row.createCell((short)i);
            cell.setCellStyle(style);
            cell.setCellValue(title[i]);
        }

        for(i = 0; i < values.length; ++i) {
            sheet.autoSizeColumn(i);
            row = sheet.createRow(i + 1);

            for(int j = 0; j < values[i].length; ++j) {
                cell = row.createCell(j);
                cell.setCellStyle(style);
                cell.setCellValue(values[i][j]);
            }
        }

    }

    public static SXSSFWorkbook getSXSSFWorkbookByThread(String[] title, String[][] values) {
        int PER_SHEET_LIMIT = 100000;
        SXSSFWorkbook wb = new SXSSFWorkbook();
        int pageNum = values.length / 100000;
        int lastCount = values.length % 100000;
        CellStyle style = wb.createCellStyle();
        style.setAlignment((short)2);
        int sheetNum = lastCount == 0 ? pageNum : pageNum + 1;
        CountDownLatch downLatch = new CountDownLatch(sheetNum);
        Executor executor = Executors.newFixedThreadPool(sheetNum);

        for(int c = 0; c <= pageNum; ++c) {
            int rowNum = 100000;
            if (c == pageNum) {
                if (lastCount == 0) {
                    continue;
                }

                rowNum = lastCount;
            }

            Sheet sheet = wb.createSheet("page" + c);
            executor.execute(new WriteTask(downLatch, sheet, title, style, rowNum, values));
        }

        try {
            downLatch.await();
        } catch (InterruptedException var13) {
            var13.printStackTrace();
        }

        return wb;
    }

    public static SXSSFWorkbook getSXSSFWorkbookByMerge(String[] title, String[][] values) {
        SXSSFWorkbook wb = new SXSSFWorkbook();
        Sheet sheet = wb.createSheet("sheet");
        CellStyle style = wb.createCellStyle();
        style.setAlignment((short)2);
        Cell cell = null;
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, 2);
        sheet.addMergedRegion(region);
        Row row = sheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("测试信息表");
        cell.setCellStyle(style);
        row = sheet.createRow(1);

        int i;
        for(i = 0; i < title.length; ++i) {
            sheet.autoSizeColumn(i);
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        for(i = 0; i < values.length; ++i) {
            sheet.autoSizeColumn(i);
            row = sheet.createRow(i + 2);

            for(int j = 0; j < values[i].length; ++j) {
                row.createCell(j).setCellValue(values[i][j]);
            }
        }

        return wb;
    }

    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "UTF-8");
            } catch (UnsupportedEncodingException var3) {
            }

            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + toUtf8String(fileName));
            response.addHeader("Pargam", "no-cache");
//            response.addHeader("Cache-Control", "no-cache");
            response.addHeader("Cache-Control", "attachment;filename=" + toUtf8String(fileName));
        } catch (Exception var4) {
            var4.printStackTrace();
        }

    }

    public static String toUtf8String(String s) {
        StringBuffer sb = new StringBuffer();

        for(int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = Character.toString(c).getBytes("utf-8");
                } catch (Exception var7) {
                    b = new byte[0];
                }

                for(int j = 0; j < b.length; ++j) {
                    int k = b[j];
                    if (k < 0) {
                        k += 256;
                    }

                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }

        return sb.toString();
    }

    public static List<ArrayList<String>> readForList(MultipartFile file) {
        String name = file.getOriginalFilename();
        String postfix = FilenameUtils.getExtension(name);
        List<ArrayList<String>> list = new ArrayList();
        if (StringUtils.equals("xlsx", postfix)) {
            list = readXlsx(file, 2);
        } else if (StringUtils.equals("xls", postfix)) {
            list = readXls(file, 2);
        }

        return (List)list;
    }

    public static List<ArrayList<String>> readForList(MultipartFile file, int rowNum) {
        String name = file.getOriginalFilename();
        String postfix = FilenameUtils.getExtension(name);
        List<ArrayList<String>> list = new ArrayList();
        if (StringUtils.equals("xlsx", postfix)) {
            list = readXlsx(file, rowNum);
        } else if (StringUtils.equals("xls", postfix)) {
            list = readXls(file, rowNum);
        }

        return (List)list;
    }

    public static List<ArrayList<String>> readXlsx(MultipartFile file, int rowNum) {
        List<ArrayList<String>> list = new ArrayList();
        InputStream input = null;
        XSSFWorkbook wb = null;

        Object var6;
        try {
            input = file.getInputStream();
            wb = new XSSFWorkbook(input);
            ArrayList<String> rowList = null;
            int totoalRows = 0;
            int totalCells = 0;

            for(int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); ++sheetIndex) {
                XSSFSheet xssfSheet = wb.getSheetAt(sheetIndex);
                if (xssfSheet != null) {
                    totoalRows = xssfSheet.getLastRowNum();

                    for(int rowIndex = rowNum - 1; rowIndex <= totoalRows; ++rowIndex) {
                        XSSFRow xssfRow = xssfSheet.getRow(rowIndex);
                        if (xssfRow != null) {
                            rowList = new ArrayList();
                            totalCells = xssfRow.getLastCellNum();

                            for(int cellIndex = 0; cellIndex < totalCells; ++cellIndex) {
                                XSSFCell xssfCell = xssfRow.getCell(cellIndex);
                                if (xssfCell == null) {
                                    rowList.add("");
                                } else {
                                    rowList.add(getValue(xssfCell));
                                }
                            }

                            list.add(rowList);
                        }
                    }
                }
            }

            return list;
        } catch (Exception var22) {
            var6 = null;
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (Exception var21) {
            }

        }

        return (List)var6;
    }

    public static List<ArrayList<String>> readXls(MultipartFile file, int rowNum) {
        List<ArrayList<String>> list = new ArrayList();
        InputStream input = null;
        HSSFWorkbook wb = null;

        Object var6;
        try {
            input = file.getInputStream();
            wb = new HSSFWorkbook(input);
            ArrayList<String> rowList = null;
            int totoalRows = 0;
            int totalCells = 0;

            for(int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); ++sheetIndex) {
                HSSFSheet hssfSheet = wb.getSheetAt(sheetIndex);
                if (hssfSheet != null) {
                    totoalRows = hssfSheet.getLastRowNum();

                    for(int rowIndex = rowNum - 1; rowIndex <= totoalRows; ++rowIndex) {
                        HSSFRow hssfRow = hssfSheet.getRow(rowIndex);
                        if (hssfRow != null) {
                            rowList = new ArrayList();
                            totalCells = hssfRow.getLastCellNum();

                            for(int cellIndex = 0; cellIndex < totalCells; ++cellIndex) {
                                HSSFCell hssfCell = hssfRow.getCell(cellIndex);
                                if (hssfCell == null) {
                                    rowList.add("");
                                } else {
                                    rowList.add(getValue(hssfCell));
                                }
                            }

                            list.add(rowList);
                        }
                    }
                }
            }

            return list;
        } catch (Exception var22) {
            var6 = null;
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (Exception var21) {
            }

        }

        return (List)var6;
    }

    public static List<HashMap<String, String>> readForMap(MultipartFile file) {
        String name = file.getOriginalFilename();
        String postfix = FilenameUtils.getExtension(name);
        List<HashMap<String, String>> readResult = null;
        if (StringUtils.equals("xlsx", postfix)) {
            readResult = readXlsxForMap(file);
        } else if (StringUtils.equals("xls", postfix)) {
            readResult = readXlsForMap(file);
        }

        return readResult;
    }

    public static List<HashMap<String, String>> readXlsForMap(MultipartFile file) {
        List<HashMap<String, String>> list = new ArrayList();
        InputStream input = null;
        HSSFWorkbook wb = null;

        Object var5;
        try {
            input = file.getInputStream();
            wb = new HSSFWorkbook(input);
            int totoalRows = 0;
            int totalCells = 0;

            for(int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); ++sheetIndex) {
                HSSFSheet hssfSheet = wb.getSheetAt(sheetIndex);
                if (hssfSheet != null) {
                    totoalRows = hssfSheet.getLastRowNum();
                    ArrayList<String> rowList = new ArrayList();
                    HSSFRow hssfRow0 = hssfSheet.getRow(0);

                    for(int cellIndex = 0; cellIndex < hssfRow0.getLastCellNum(); ++cellIndex) {
                        HSSFCell hssfCell = hssfRow0.getCell(cellIndex);
                        if (hssfCell == null) {
                            rowList.add("");
                        } else {
                            rowList.add(getValue(hssfCell));
                        }
                    }

                    HashMap<String, String> rowMap = null;

                    for(int rowIndex = 1; rowIndex <= totoalRows; ++rowIndex) {
                        HSSFRow hssfRow = hssfSheet.getRow(rowIndex);
                        if (hssfRow != null) {
                            rowMap = new HashMap();
                            totalCells = hssfRow.getLastCellNum();

                            for(int cellIndex = 0; cellIndex < totalCells; ++cellIndex) {
                                HSSFCell hssfCell = hssfRow.getCell(cellIndex);
                                if (hssfCell == null) {
                                    rowMap.put(rowList.get(cellIndex), "");
                                } else if (hssfCell.getCellType() == 0 && HSSFDateUtil.isCellDateFormatted(hssfCell)) {
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                    rowMap.put(rowList.get(cellIndex), sdf.format(hssfCell.getDateCellValue()));
                                } else {
                                    hssfCell.setCellType(1);
                                    rowMap.put(rowList.get(cellIndex), String.valueOf(hssfCell.getStringCellValue()));
                                }
                            }

                            list.add(rowMap);
                        }
                    }
                }
            }

            return list;
        } catch (Exception var24) {
            var5 = null;
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (Exception var23) {
            }

        }

        return (List)var5;
    }

    public static List<HashMap<String, String>> readXlsxForMap(MultipartFile file) {
        List<HashMap<String, String>> list = new ArrayList();
        InputStream input = null;
        XSSFWorkbook wb = null;

        Object var5;
        try {
            input = file.getInputStream();
            wb = new XSSFWorkbook(input);
            int totoalRows = 0;
            int totalCells = 0;

            for(int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); ++sheetIndex) {
                XSSFSheet xssfSheet = wb.getSheetAt(sheetIndex);
                if (xssfSheet != null) {
                    totoalRows = xssfSheet.getLastRowNum();
                    ArrayList<String> rowList = new ArrayList();
                    XSSFRow xssfRow0 = xssfSheet.getRow(0);

                    for(int cellIndex = 0; cellIndex < xssfRow0.getLastCellNum(); ++cellIndex) {
                        XSSFCell xssfCell = xssfRow0.getCell(cellIndex);
                        if (xssfCell == null) {
                            rowList.add("");
                        } else {
                            rowList.add(getValue(xssfCell));
                        }
                    }

                    HashMap<String, String> rowMap = null;

                    for(int rowIndex = 1; rowIndex <= totoalRows; ++rowIndex) {
                        XSSFRow xssfRow = xssfSheet.getRow(rowIndex);
                        if (xssfRow != null) {
                            rowMap = new HashMap();
                            totalCells = xssfRow.getLastCellNum();

                            for(int cellIndex = 0; cellIndex < totalCells; ++cellIndex) {
                                XSSFCell xssfCell = xssfRow.getCell(cellIndex);
                                if (xssfCell == null) {
                                    rowMap.put(rowList.get(cellIndex), "");
                                } else if (xssfCell.getCellType() == 0 && HSSFDateUtil.isCellDateFormatted(xssfCell)) {
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                    rowMap.put(rowList.get(cellIndex), sdf.format(xssfCell.getDateCellValue()));
                                } else {
                                    xssfCell.setCellType(1);
                                    rowMap.put(rowList.get(cellIndex), String.valueOf(xssfCell.getStringCellValue()));
                                }
                            }

                            list.add(rowMap);
                        }
                    }
                }
            }

            return list;
        } catch (Exception var24) {
            var5 = null;
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (Exception var23) {
            }

        }

        return (List)var5;
    }

    private static String getValue(Cell cell) {
        if (cell.getCellType() == 4) {
            return String.valueOf(cell.getBooleanCellValue());
        } else {
            return cell.getCellType() == 0 ? String.valueOf(cell.getNumericCellValue()) : String.valueOf(cell.getStringCellValue());
        }
    }

    public static String getPostfix(String path) {
        return !StringUtils.isBlank(path) && path.contains(".") ? path.substring(path.lastIndexOf(".") + 1, path.length()).trim() : null;
    }

    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

    public static boolean validateExcel(String filePath) {
        return filePath != null && (isExcel2003(filePath) || isExcel2007(filePath));
    }

    public static CopyOnWriteArrayList readByThread(Class c, String[] property, MultipartFile file) throws Exception {
        return readByThread(c, property, file, 1, 0);
    }

    public static CopyOnWriteArrayList readByThread(Class c, String[] property, MultipartFile file, int startRow, int startColumn) throws Exception {
        CopyOnWriteArrayList beanList = new CopyOnWriteArrayList();
        String fileName = file.getOriginalFilename();
        Workbook wb = null;
        if (null != file) {
            InputStream is = file.getInputStream();
            if (fileName.endsWith(".xls")) {
                wb = new HSSFWorkbook(is);
            } else if (fileName.endsWith(".xlsx")) {
                wb = new XSSFWorkbook(is);
            }
        }

        if (wb != null) {
            int runSize = ((Workbook)wb).getNumberOfSheets();
            ExecutorService executor = Executors.newFixedThreadPool(runSize);
            CountDownLatch countDownLatch = new CountDownLatch(runSize);

            for(int i = 0; i < runSize; ++i) {
                executor.execute(new ReadByClassTask(c, i, countDownLatch, property, (Workbook)wb, startRow, startColumn, beanList));
            }

            try {
                countDownLatch.await();
            } catch (InterruptedException var12) {
            }

            executor.shutdown();
        }

        return beanList;
    }

    public static List<ArrayList<String>> readByThread(MultipartFile file) throws Exception {
        return readByThread(file, 1, 0);
    }

    public static List<ArrayList<String>> readByThread(MultipartFile file, int startRow, int startColumn) throws Exception {
        List<ArrayList<String>> beanList = new ArrayList();
        String fileName = file.getOriginalFilename();
        Workbook wb = null;
        if (null != file) {
            InputStream is = file.getInputStream();
            if (fileName.endsWith(".xls")) {
                wb = new HSSFWorkbook(is);
            } else if (fileName.endsWith(".xlsx")) {
                wb = new XSSFWorkbook(is);
            }
        }

        if (wb != null) {
            int runSize = ((Workbook)wb).getNumberOfSheets();
            ExecutorService executor = Executors.newFixedThreadPool(runSize);
            CountDownLatch countDownLatch = new CountDownLatch(runSize);

            for(int i = 0; i < runSize; ++i) {
                executor.execute(new ReadForListTask(i, countDownLatch, (Workbook)wb, startRow, startColumn, beanList));
            }

            try {
                countDownLatch.await();
            } catch (InterruptedException var10) {
            }

            executor.shutdown();
        }

        return beanList;
    }
}
